import React, {useEffect, useState,useRef,useReducer} from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  ScrollView,
  FlatList,
  TouchableOpacity,
  Dimensions,
  ImageBackground
} from 'react-native';
import {connect, ConnectedProps} from 'react-redux';
import {IArticals} from '../../models/articals';
import {RootState} from '@/models/index';
import LinearGradient from 'react-native-linear-gradient';
import Touchable from '../../components/Touchable';
import {IUserInfo} from '@/models/user';
import {getWidth} from '../../utils/index';
import Video from 'react-native-video';
import AsyncStorage from '@react-native-async-storage/async-storage';
import IconFont,{IconNames} from "../../assets/iconfont";
const mapStateToProps = ({users,articals,loading}: RootState) => {
  return {
    currentUser1:users?.user,
    articals: articals?.articals,
    // 在触发getGoodsList方法时加上加载效果
    loading: loading.effects['articals/getArticalsList'],
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState {
  navigation: {navigate: any};
  route:any
}
interface IA extends IArticals {
  username?: string;
  scurpture?: string;
}

function VideoPlayer(props:any) {
  const [playing, setPlaying] = useState(false); // 控制视频播放状态
  const videoRef = useRef<Video>(null);
  const handlePlay = (url:any) => {
    setPlaying(true);
  };
  const handlePause = () => {
    setPlaying(false);
  };
  return (
    <View style={{ flex:1}}>
      <Video
        source={{ uri: props.videoUrl }}
        posterResizeMode='contain'
        poster="https://img1.baidu.com/it/u=744982176,2317964104&fm=253&fmt=auto&app=138&f=JPEG?w=499&h=334"
        onEnd={() => {
          // 当视频播放结束时，重置播放状态
          setPlaying(false);
        }}
        ref={videoRef}
        paused={!playing}
        resizeMode="contain"
        style={styles.video}
      />
      <View style={{width:40,height:40}}>
        {playing ? (
          <TouchableOpacity onPress={handlePause}>
            <Image
              source={require('../../assets/localImage/play.png')}
              style={{width:30,height:30}}
            />
          </TouchableOpacity>
        ) : (
          <TouchableOpacity onPress={() => handlePlay(props.videoUrl)}>
            <Image
              source={require('../../assets/localImage/paused.png')}
              style={{width:30,height:30}}
            />
          </TouchableOpacity>
        )}
      </View>
    </View>
  );
}



function Like(props: IProps) {
  const {dispatch,navigation,currentUser1,route} = props;
  const [imageArticals, setImageAricals] = useState<IA[]>([]);
  const [videoArticals, setVideoArticals] = useState<IA[]>([]);
  const [isImage, setIsImage] = useState<boolean>(true);
  const [users, setUsers] = useState<IUserInfo[]>();
  const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
  function handleClick() {
  forceUpdate();
  }
  useEffect(() => {
    dispatch({
      type: 'articals/getArticalsList',
      callback: (newArticals: IA[]) => {
        // console.log("圈子拿到了文章数据",articals);
        // 分成图片数据和视频数据
        if(currentUser1 && currentUser1[0].Like){
          let articals:any[] = [];
          newArticals.forEach( i => {
            currentUser1[0].Like?.forEach(j => {
              if(i._id === j) {
                articals.push(i)
              }
            })
          });
          console.log("articals",articals)
          const imageArticals = articals.filter(i => {
            return i.type === 'image';
          });
          setImageAricals(imageArticals);
          const videoArticals = articals.filter(v => {
            return v.type === 'video';
          });
          setVideoArticals(videoArticals);
          dispatch({
            type: 'users/getUserInfo',
            callback: (users: IUserInfo[]) => {
              console.log('获取到了user', users);
              users.map(u => {
                let newImages = imageArticals;
                let newVideos = videoArticals;
                newImages.map(i => {
                  if (i.owner_id === u._id) {
                    // 加入username和头像
                    i.username = u.username;
                    i.scurpture = u.scurpture;
                  }
                });
                newVideos.map(v => {
                  if (v.owner_id === u._id) {
                    // 加入username和头像
                    v.username = u.username;
                    v.scurpture = u.scurpture;
                  }
                });
                setImageAricals(newImages);
                setVideoArticals(newVideos);
              });
              setUsers(users);
            },
          });
        }
      },
    });
  },[ignored]);
  const handleImage = () => {
    setIsImage(true);
  };
  const handleVideo = () => {
    setIsImage(false);
  };
  const handleClickImage = (i:IArticals) => {
    console.log("handleClickImage",i);
    navigation.navigate("ImageInfo",{
      selectItem:i,
      handleClick:handleClick
    });
  }
  // const handleAddArtical = async() => {
  //   // 发表文章应该先检查当前用户是否登录
  //   // const token = await AsyncStorage.getItem('token');
  //   if(JSON.stringify(currentUser1) !== "[]"){
  //     // 直接刷新页面token还是存在，需要退出登录才能清空token
  //     navigation.navigate("AddArtical",{
  //       user_id: currentUser1 && currentUser1[0] && currentUser1[0]._id ? currentUser1[0]._id : "",
  //       handleClick:handleClick
  //     });
  //   }else {
  //     navigation.navigate("Login")
  //   }
  // }
  const sliceArr= (arr:any[]) =>{
    let newArr = arr.slice(0,3);
    return newArr
  }
  return (
    <View style={styles.circle}>
      <LinearGradient
        colors={['#fff', '#A75E5E']}
        style={styles.linearGradient}>
     <View style={styles.header}>
     <View style={styles.tab}>
          <Touchable onPress={handleImage}>
            <Text style={isImage ? styles.highColor : styles.tabText}>
              图片
            </Text>
          </Touchable>
          <Touchable onPress={handleVideo}>
            <Text style={isImage ? styles.tabText : styles.highColor}>
              视频
            </Text>
          </Touchable>
        </View>
        {/* <Touchable onPress={handleAddArtical}>
           <IconFont name="icon-tianjiatianchong" size={24} color="#A75E5E" />
          </Touchable> */}
     </View>
        {isImage ? (
          <ScrollView style={styles.iBox}>
            {imageArticals.map(i => {
              return (
                <Touchable style={styles.iItem} key={i._id} onPress={()=>{handleClickImage(i)}}>
                  <View style={styles.imageBox}>
                    {i.artical_images &&
                      sliceArr(i.artical_images).map(image => {
                        return (
                          <Image
                            source={{uri: image.i_url}}
                            key={image.i_url}
                            style={styles.image}></Image>
                        );
                      })}
                  </View>
                  <View style={styles.bottomBox}>
                    <Image
                      source={{uri: i.scurpture}}
                      style={styles.scurpture}></Image>
                    <View style={styles.textBox}>
                      <Text style={styles.title}>{i.artical_title && i.artical_title.length >13 ? `${i.artical_title.substring(0,13)}...`:i.artical_title}</Text>
                      <Text>{i.artical_detail && i.artical_detail.length >26 ? `${i.artical_detail.substring(0,26)}...`:i.artical_detail}</Text>
                    </View>
                  </View>
                </Touchable>
              );
            })}
          </ScrollView>
        ) : (
          <ScrollView>
            <View style={styles.container}>
            {videoArticals.map((i) => {
              return (
                <View style={styles.iItem} key={i._id}>
                  <View style={styles.imageBox}>
                    {i.artical_videos &&
                      i.artical_videos.map(video => {
                        return (
                          <VideoPlayer
                          key={video.aid}
                          videoUrl={video.a_url}
                        />
                        );
                      })}
                  </View>
                  <View style={styles.bottomBox}>
                    <Image
                      source={{uri:i.scurpture}}
                      style={styles.scurpture}></Image>
                    <View style={styles.textBox}>
                      <Text style={styles.title}>{i.artical_title}</Text>
                      <Text>{i.artical_detail}</Text>
                    </View>
                  </View>
                </View>
              );
            })}
          </View>
          </ScrollView>
        )}
      </LinearGradient>
    </View>
  );
}
const styles = StyleSheet.create({
  circle: {
    flex: 1,
  },
  linearGradient: {
    width: '100%',
    height: '100%',
    paddingHorizontal: 15,
    borderRadius: 5,
    marginBottom: 40,
  },
  header:{
    display:"flex",
    flexDirection:"row",
    justifyContent: 'center',
    alignItems: 'center',
  },
  tab: {
    width:getWidth(80),
    display: 'flex',
    flexDirection: 'row',
    height: 45,
    justifyContent: 'center',
    alignItems: 'center',
  },
  tabText: {
    fontSize: 18,
    color: 'black',
    paddingHorizontal: 6,
  },
  highColor: {
    color: '#A75E5E',
    paddingHorizontal: 6,
    fontSize: 18,
    borderBottomColor: '#A75E5E',
    borderBottomWidth: 1,
  },
  iBox: {
    // backgroundColor:"#fff",
  },
  iItem: {
    marginVertical: 5,
    borderRadius: 5,
    backgroundColor: '#fff',
    paddingTop: 10,
    width:"100%",
  },
  imageBox: {
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingHorizontal: 8,
    width:"100%",
  },
  image: {
    width: "31%",
    height: 100,
    borderRadius: 5,
    marginHorizontal: "1%",
    marginVertical: 4,
  },
  scurpture: {
    width: 50,
    height: 50,
    borderRadius: 50,
    marginRight: 10,
  },
  bottomBox: {
    display: 'flex',
    flexDirection: 'row',
    paddingVertical: 10,
    alignItems: 'center',
    paddingRight: 20,
    backgroundColor: '#F6F2F2',
    paddingLeft: 10,
    borderRadius: 5,
  },
  title: {
    fontSize: 16,
    fontWeight: '700',
  },
  textBox: {
    width: getWidth(65),
  },
  container: {
    width:"100%",
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  video: {
    width: "100%",
    height: 200,
  },
});
export default connector(Like);
